function cutpath = cutmat(matpath,cutdim_char,max_ind,options)
%Thomas Stevens - Lim Lab. Opened 012413
% Cut a cell array mat files along specified dimension
% - because ND arrays are slow to read/write/process if not operating on all dims
% Currently only addresses time dimension
%INPUT: matfile path, in order of concatenation,
%       dimension to use: 'x','y','z','t','c','p'
%OUTPUT: path to a new matfile containing the concatenation
% e.g.
% matpath = '/Users/ucsf/Desktop/Lim/All_Lim_Microscopy/Yeast/011513_yTS27g-39_growth_all.mat';
% cutpath = cutmat(matpath,'t',45);

if nargin<1 || isempty(matpath)
    [file,path] = uigetfile();
    matpath = {[path file]};
end
if nargin < 4 || ~iscell(options)
    options = {''};
end

if ischar(matpath), matpath = {matpath}; end
if ischar(options), options = {options}; end

isParallel = startParallel(options);

%Define dimension characters
%dimstr = 'xyztc';
%cutdim_num = find(cutdim_char==dimstr);
cutpath = [matpath{1}(1:strfind(matpath{1},'.mat')-1) '_cut.mat'];
%Copy entire file, then delete contents iteratively
if ~exist(cutpath,'file')
    disp('Copying entire matfile to subset...')
    tic
    copyfile(matpath{1},cutpath);
    toc
end

for i=1:length(matpath)
    m{i} = matfile(matpath{i});
    w{i} = who('-file',matpath{i});
    if i==1
        ixns = w{i};
    else
        ixns = intersect(ixns,w{i});
    end
    s = m{i}.s;
    cellsize(i,:) = [s.x s.y s.z s.time s.channels s.positions];
end

if cutdim_char=='t'
    %Cut I{p}
    if ismember('I',ixns)    
        parfor p=1:s.positions
            disp(['Cutting I along interior dimension ' cutdim_char ', p=' num2str(p)])
            tic
            %have to reopen file inside parfor
            cutfile = matfile(cutpath,'Writable',true);
            I_p = cell2mat(cutfile.I(p,1));
            cutfile.I(p,1) = {I_p(:,:,:,1:max_ind,:)};
            toc
        end
        clear cutfile
    end
    %Cut BW{c,p}
    if ismember('BW',ixns)
        %broadcast variable for inner limits
        channels = s.channels;
        parfor p=1:s.positions
            for c=1:channels
            disp(['Cutting BW along interior dimension ' cutdim_char ', p=' num2str(p) ', c=' num2str(c)])
            tic
            %have to reopen file inside parfor
            cutfile = matfile(cutpath,'Writable',true);
            BW_cp = cell2mat(cutfile.BW(c,p));
            cutfile.BW(c,p) = {BW_cp(:,:,:,1:max_ind)};
            toc
            end
        end
        clear cutfile
    end
    
    disp('Cutting s, & time_v along interior dimension...')
    %have to reopen file outside parfor
    cutfile = matfile(cutpath,'Writable',true);
    %Cut s.time
    cutfile_s = m{1}.s;
    cutfile_s.time = max_ind;
    cutfile.s = cutfile_s;
    %Cut time_v
    cutfile.time_v = cutfile.time_v(1:max_ind,:,:);
end

%matlabpool close

end